<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/4/9
 * Time: 14:13
 */

namespace Biz\service;

use Biz\cache\CarouselBanner as cCarouselBanner;
use Biz\model\ShopCarouselBanner as mShopCarouselBanner;
use Biz\model\ShopCarouselBanner;
use Biz\model\ShopCategoryClassify;
use Biz\service\activity\FlashSale;
use Doraemon\tools\ImgUrl;
use Biz\validate\ShopBanner as vShopBanner;
use Biz\tools\Link as tLink;
use Biz\model\ShopCarouselBannerPos as mShopCarouselBannerPos;
use Doraemon\service\User as sUser;
use Biz\module\Classes\User;
use Biz\service\Goods as sGoods;
use Biz\service\activity\PinTuan as sPinTuan;
use Biz\model\ShopBannerGrabConfig as mShopBannerGrabConfig;
use Biz\service\esSearch\Goods as esGoods;
/**
 * @deprecated
 */
class CarouselBanner
{
	const BANNER_CACHHE_NAME = 'carouselbanner';
	const VISIBLE_BANNER_CACHE_NAME = 'visiblebanner';
	const NEW_USER_NAMMER_CACHE_NAME = 'newuserbanner';
	const ACTIVITY_BANNER_CACHE_NAME = 'activitybanner';
	const MEAL_BANNER_CACHE_NAME = 'mealbanner';
	const BANNER_POS_CACHE_NAME = 'bannerpos';
	public static $bannerList = [];

	public static function getBanner($uid, $time)
	{

		/*
		 * N小时内注册可见逻辑
		 * **/
		{
			$visibleList = [];

			$visibleCacheBannerData = cCarouselBanner::getBanner(self::VISIBLE_BANNER_CACHE_NAME);
			if (is_null($visibleCacheBannerData)) {
				$visibleData = mShopCarouselBanner::getCarouselBannerByVisible($time, mShopCarouselBanner::WIKI_STATUS_INVISIBLE);
                $visibleCacheBannerData = self::formatBanner($visibleData);
				cCarouselBanner::setBanner(self::VISIBLE_BANNER_CACHE_NAME, $visibleCacheBannerData);
			}

			if ($visibleCacheBannerData) {
				if (!$uid) {
					$visibleList = $visibleCacheBannerData;
				} else {
					if ($visibleCacheBannerData) {
						$userInfo = sUser::getUser($uid);
						$visibleTime = time() - $userInfo['addtime'];
						foreach ($visibleCacheBannerData as $value) {
							if (($value['visible_time'] - $visibleTime) >= 0) {
								$visibleList[] = $value;
							}
						}
					}
				}
			}

			$visibleCount = count($visibleList);

			$count = mShopCarouselBanner::MAX_COUNT - ($visibleCount);

		}

		/*
		 * 未下单用户可见逻辑
		 * **/
		{
			$newUserVisibleList = [];

			$newUserCacheList = cCarouselBanner::getBanner(self::NEW_USER_NAMMER_CACHE_NAME);
			if (is_null($newUserCacheList)) {
				$newUserList = mShopCarouselBanner::getCarouselBannerByVisible($time, mShopCarouselBanner::NEW_USER_VISIBLE);
                $newUserCacheList = self::formatBanner($newUserList);
				cCarouselBanner::setBanner(self::NEW_USER_NAMMER_CACHE_NAME, $newUserCacheList);
			}

			if ($newUserCacheList) {
				$isNewUser = true;
				if ($uid) {
					$isNewUser = User::isNewUser($uid);
				}

				if (!$uid || $isNewUser) {
					$newUserVisibleList = $newUserCacheList;
				}
			}

			$count = $count - count($newUserVisibleList);
		}

		/*
		 * 所有用户可见逻辑
		 * **/
		{
			$carouselBannerList = cCarouselBanner::getBanner(self::BANNER_CACHHE_NAME);
			if (is_null($carouselBannerList)) {
				$carouselBanner = self::getCarouselBanner($time, $count) ?: [];
                $carouselBannerList = self::formatBanner($carouselBanner);
				cCarouselBanner::setBanner(self::BANNER_CACHHE_NAME, $carouselBannerList);

			}
		}

		$carouselBannerList = $carouselBannerList ?: [];
		$visibleList = $visibleList ?: [];
		$newUserVisibleList = $newUserVisibleList ?: [];

		$list = array_merge($visibleList, $newUserVisibleList, $carouselBannerList);

		return $list ?: [];
	}

    private static function formatBanner($visibleData)
    {
        $result = [];
        foreach ($visibleData as $info) {
            self::formatInfo($info);
            $info['link'] = self::formatLink($info['link_type'], $info['link_dest'], $info['visible_user']);
            $info['statType'] = $info['type'] . '-' . $info['show_type'];
            $info['statSign'] = self::formatStatSign($info);
            unset($info['link_dest']);
            $result[] = $info;
        }
        return $result;
    }

	public static function getMultipleBanner($uid, $time, $areaCode = 0)
	{
		// 获取banner位置信息
		$posList = cCarouselBanner::getBanner(self::BANNER_POS_CACHE_NAME);
		if (is_null($posList)) {
			$posList = mShopCarouselBannerPos::select('*', ['status' => mShopCarouselBannerPos::STATUS_NORMAL, 'ORDER' => ['sort' => 'DESC']]);
			cCarouselBanner::setBanner(self::BANNER_POS_CACHE_NAME, $posList);
		}

		// 获取活动banner信息
		$list = cCarouselBanner::getBanner(self::ACTIVITY_BANNER_CACHE_NAME);
		if (is_null($list)) {
			$carouselBanner = mShopCarouselBanner::getMultipleBanner($time);
			$expire = cCarouselBanner::_CACHE_EXPIRE_TIME;
            $list = [];
			foreach ($carouselBanner as $info) {
				//获取最小的缓存过期时间
				$expire = self::getCarouseBannerExpire($expire, $info);
				self::formatInfo($info);
				$info['link'] = self::formatLink($info['link_type'], $info['link_dest']);
				unset($info['link_dest'], $info['start_time'], $info['end_time']);
				$list[] = $info;
			}
			cCarouselBanner::setBanner(self::ACTIVITY_BANNER_CACHE_NAME, $list, $expire);
		}

		$userInfo = sUser::getUser($uid);
		$visibleTime = time() - $userInfo['addtime'];
		$isNewUser = true;
		if ($uid) {
			$isNewUser = User::isNewUser($uid);
		}
		// 处理位置与类型的对应关系 && 判断新老用户可见banner
		$data = [];
		foreach ($posList as $value) {
			foreach ($list as $val) {
				// N小时内注册用户可见逻辑
				if ($val['show_type'] == $value['id']) {
					if ($val['visible_user'] == mShopCarouselBanner::STATUS_VISIBLE) {
						$data[$value['id']][] = $val;
					} else if (mShopCarouselBanner::WIKI_STATUS_INVISIBLE && ($uid == 0 || $val['visible_time'] - $visibleTime >= 0)) {
						$data[$value['id']][] = $val;
					} else if (mShopCarouselBanner::NEW_USER_VISIBLE && ($uid == 0 || $isNewUser)) {
						$data[$value['id']][] = $val;
					}
				}
			}
		}

		$posList = array_column($posList, null, 'id');
        $bannerList = [];
		// 构造banner数据
		foreach ($data as $value) {
			foreach ($value as $val) {
			    switch ($val['type']) {
                    case mShopCarouselBanner::TYPE_ONE :
                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_ONE, $val, 'mall_banner_list');
                        break;
                    case mShopCarouselBanner::TYPE_THREE :
                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_THREE, $val, 'mall_recommend_list');
                        break;
                    case mShopCarouselBanner::TYPE_FOUR :
                        $val['banner_desc'] = str_replace("^", "\n", $val['banner_desc']);
                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_FOUR, $val, 'mall_activity_list');
                        break;
                    case mShopCarouselBanner::TYPE_FIVE_POSITION :
                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_FIVE_POSITION, $val, 'mall_five_position_list');
                        break;
                    case mShopCarouselBanner::TYPE_TWO_ONELINE :
                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_TWO_ONELINE, $val, 'mall_two_oneline');
                        break;
                    case mShopCarouselBanner::TYPE_CART_SUSPENSION :
                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_CART_SUSPENSION, $val, 'cart_suspension');
                        break;
                    case mShopCarouselBanner::TYPE_SUMITOMO_IS_BUYING :
                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_SUMITOMO_IS_BUYING, $val, 'mall_sumitomo_is_buying');
                        break;
//                    case mShopCarouselBanner::TYPE_SEARCH_RESULTS :
//                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_SEARCH_RESULTS, $val, 'search_results');
//                        break;
                    case mShopCarouselBanner::TYPE_FLASH_MODULE :
                        $FlashSaleModule = FlashSale::flashInfoOnShop();
                        if (!$FlashSaleModule || !$FlashSaleModule['goods_list']) {
                            break;
                        }
                        $bannerList['type'] = mShopCarouselBanner::TYPE_FLASH_MODULE;
                        $bannerList['flash_sale_module'] = $FlashSaleModule;
                        $bannerList['flash_sale_module']['banner'] = $val['banner'];
                        $bannerList['flash_sale_module']['icon'] = 'http://img.hhz1.cn/Op-imageShow/9330e30290100uJ00pjme32?iv=1';
                        $bannerList['flash_sale_module']['statSign'] = self::formatStatSign($val);
                        break;
                    case mShopCarouselBanner::TYPE_FLASH_SALE :
                        $bannerList = self::formatBannerList(mShopCarouselBanner::TYPE_FLASH_SALE, $val, 'flash_sale');
                        break;
                    case mShopCarouselBanner::TYPE_GOODS_LIST :
                        $goodsInfo = self::grabGoods($val, $areaCode);
                        $bannerList['type'] = mShopCarouselBanner::TYPE_GOODS_LIST;
                        $bannerList['goods_list_module'] = [
                            'title' => $posList[$val['show_type']]['module_title'],
                            'banner_desc' => $posList[$val['show_type']]['module_subtitle'],
                            'banner' => $val['banner'],
                            'id' => $val['id'],
                            'link' => $val['link'],
                            'icon' => 'http://img.hhz1.cn/Op-imageShow/9330e30290100uJ00pjme32?iv=1',
                            'statSign' => self::formatStatSign($val),
                            'statType' => mShopCarouselBanner::TYPE_GOODS_LIST . '_' . $val['show_type'],
                            'goods_list' => $goodsInfo,
                        ];
                        break;
                    case mShopCarouselBanner::TYPE_THREE_TITLE :
                        $bannerList['type'] = mShopCarouselBanner::TYPE_THREE_TITLE;
                        $bannerList['three_position_module']['title'] = $posList[$val['show_type']]['module_title'];
                        $bannerList['three_position_module']['banner_desc'] = $posList[$val['show_type']]['module_subtitle'];

                        $goodsInfo = self::grabGoods($val, $areaCode);
                        $val['banner'] = $goodsInfo ? current($goodsInfo)['cover_img'] : '';
                        $val['statType'] = $goodsInfo ? current($goodsInfo)['statType'] : '';
                        $val['banner_desc'] = str_replace("^", "\n", $val['banner_desc']);
                        $val['statSign'] = self::formatStatSign($val);
                        $bannerList['three_position_module']['banner_list'][] = $val;
                        break;
                    case mShopCarouselBanner::TYPE_PINTUAN :
                        $pinTuanList = sPinTuan::getList(sPinTuan::LIST_COUNT);
                        if(!$pinTuanList) {
                            break;
                        }
                        $pinTuanList = array_map(function ($pinTuan) use ($val){
                            $pinTuan['statType'] = mShopCarouselBanner::TYPE_PINTUAN . '_' . $val['show_type'];
                            $pinTuan['statSign'] = self::formatStatSign($val, $pinTuan['id']);
                            return $pinTuan;
                        }, $pinTuanList);
                        $bannerList['type'] = mShopCarouselBanner::TYPE_PINTUAN;
                        $bannerList['pintuan_module'] = [
                            'icon' => 'http://img.hhz1.cn/Op-imageShow/9330e30290100uJ00pjme32?iv=1',
                            'banner' => $val['banner'],
                            'statSign' => self::formatStatSign($val),
                            'statType' => mShopCarouselBanner::TYPE_PINTUAN . '_' . $val['show_type'],
                            'id' => $val['id'],
                            'link' => $val['link'],
                            'goods_list' => $pinTuanList
                        ];
                        break;
                }
				if ($val['type'] == mShopCarouselBanner::TYPE_ONE) {
					$activityBannerData[] = $bannerList;
                    $bannerList = [];
                    self::$bannerList = [];
				}
			}

			if ($val['type'] != mShopCarouselBanner::TYPE_ONE) {
			    // 如果是一行两个的话需要返回2的倍数
			    if($val['type'] == mShopCarouselBanner::TYPE_TWO_ONELINE) {
			        if(count($bannerList['mall_two_oneline']) <= 1) {
			            continue;
                    }
			        if(count($bannerList['mall_two_oneline']) % 2 == 1) {
			            array_pop($bannerList['mall_two_oneline']);
                    }
                }else if ($val['type'] == mShopCarouselBanner::TYPE_THREE) {
			        if(count($bannerList['mall_recommend_list']) <=2) {
			            continue;
                    }
                    $length = (count($bannerList['mall_recommend_list'])) - count($bannerList['mall_recommend_list']) % 3;
                    $bannerList['mall_recommend_list'] = array_slice($bannerList['mall_recommend_list'], 0, $length);
                }

				$activityBannerData[] = $bannerList;
                $bannerList = [];
				self::$bannerList = [];
			}
		}

		return $activityBannerData ? array_filter($activityBannerData) : [];
	}

    /**
     * 处理banner统计相关信息
     * @param $type
     * @param $info
     * @param $key
     * @return mixed
     */
    private static function formatBannerList($type, $info, $key)
    {
        $banner['id'] = $info['id'];
        $banner['title'] = $info['title'];
        $banner['banner_desc'] = $info['banner_desc'];
        $banner['type'] = $info['type'];
        $banner['banner'] = $info['banner'];
        $banner['link'] = $info['link'];
        $banner['commend'] = $info['commend'];
        $banner['statType'] = $type . '-' . $info['show_type'];
        $banner['statSign'] = self::formatStatSign($info);


        self::$bannerList['type'] = $type;
        self::$bannerList[$key][] = $banner;
        return self::$bannerList;
    }

    private static function formatStatSign($info, $goodsId = 0)
    {
        return json_encode([
            'id' => $info['id'],
            'weight' => $info['sort'],
            't' => 'adClk',
            'app' => 'mall',
            'comment' => $info['comment'] ? : '',
            'posiSign' => $info['type'] . '-' . $info['show_type'] . '-' . $info['sort'] . '-' . $goodsId,
        ], JSON_UNESCAPED_UNICODE);
    }

	private static function grabGoods($info, $areaCode)
    {
        $goodsInfos = [];
        if ($info['is_grab'] == ShopCarouselBanner::NO_GRAB) {
            if($info['goods_id']) {
                $goodsIds = explode(',', $info['goods_id']);
                if($info['style'] == mShopCarouselBanner::STYLE_ONE) {
                    $goodsIds = array_slice($goodsIds, 0,3);
                } else {
                    $goodsIds = array_slice($goodsIds, 0,6);
                }
                $goodsInfos = sGoods::goods($goodsIds, sGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode]);
                $goodsInfos = $goodsInfos ? array_values($goodsInfos) : [];
            }
        } else if($info['is_grab'] == ShopCarouselBanner::IS_GRAB) {
            // 查询配置的数据，查询出来之后，根据类型和数据去抓取商品
            $configInfo = mShopBannerGrabConfig::getInfo(['banner_id' => $info['id'], 'status' => mShopBannerGrabConfig::STATUS_NORMAL]);
            if(!is_null($configInfo)) {
                if($configInfo['grab_type'] == mShopBannerGrabConfig::TYPE_CATEGORY) {
                    $categoryList = Category::getCateIdsByClassifyId($configInfo['tags']);
                    $where = [
                        'second_category_id' => $categoryList['cate_ids'],
                        'source' => esGoods::SOURCE_APP
                    ];
                    $goodsIds = SearchGoods::searchEntrance($where, esGoods::SCENES_CATEGORY_ID, 0, 1,$info['style'] == mShopCarouselBanner::STYLE_ONE ? 3: 6);
                    $goodsInfos = sGoods::Goods($goodsIds['rows']);
                    $goodsInfos = $goodsInfos ? array_values($goodsInfos) : [];
                } else if($configInfo['grab_type'] == mShopBannerGrabConfig::TYPE_KEYWORD) {
                    $goodsInfos = MallGoodsList::RecommendByKeyWordFormBanner($configInfo['tags'], $info['style'] == mShopCarouselBanner::STYLE_ONE ? 3: 6, $areaCode);
                    $goodsInfos =  $goodsInfos['list'] ? : [];
                } else if($configInfo['grab_type'] == mShopBannerGrabConfig::TYPE_TAGS) {
                    $goodsInfos = MallGoodsList::RecommendByTag($configInfo['tags'], 1, $info['style'] == mShopCarouselBanner::STYLE_ONE ? 3: 6, 0, $areaCode);
                    $goodsInfos =  $goodsInfos['list'] ? : [];
                }
            }
        }

        return $goodsInfos ? $goodsInfo = array_map(function ($goodsInfo) use ($info){
            $goodsInfo['statType'] = mShopCarouselBanner::TYPE_GOODS_LIST . '_' . $info['show_type'];
            $goodsInfo['statSign'] = self::formatStatSign($info, $goodsInfo['id']);
            return $goodsInfo;
        }, $goodsInfos) : [];
    }

	public static function getBannerByType($type)
	{
		$list = cCarouselBanner::getBanner(self::MEAL_BANNER_CACHE_NAME);
		if (is_null($list)) {
			$carouselBanner = mShopCarouselBanner::getBannerByType($type);
			foreach ($carouselBanner as $info) {
				self::formatInfo($info);
				$info['link'] = self::formatLink($info['link_type'], $info['link_dest']);
				$info['statType'] = mShopCarouselBanner::TYPE_MEAL . '-' . $info['show_type'];
				$info['statSign'] = self::formatStatSign($info);
				unset($info['link_dest']);
				$list[] = $info;
			}
			$expire = $list ? strtotime(reset($list)['end_time']) - time() : cCarouselBanner::_CACHE_EXPIRE_TIME;
			cCarouselBanner::setBanner(self::MEAL_BANNER_CACHE_NAME, $list, $expire);
		}

		return $list;
	}

	public static function admGetBannerInfoById($id)
	{
		$bannerInfo = mShopCarouselBanner::getBannerInfoById($id);
		$bannerInfo['banner_hash'] = $bannerInfo['banner'] ?: '';
		self::formatInfo($bannerInfo);
		$configInfo = mShopBannerGrabConfig::getInfo(['banner_id' => $id, 'status' => mShopBannerGrabConfig::STATUS_NORMAL]);
		if($configInfo) {
		    $bannerInfo['grab_type'] = $configInfo['grab_type'];
		    $bannerInfo['tags'] = $configInfo['tags'];
        }

		return $bannerInfo;
	}

	public static function admGetBannerList($data, $limit)
	{
		$bannerList = [];
		$bannerData = mShopCarouselBanner::getBannerList($data, $limit);
		$bannerData = self::getCalculationDiff($bannerData);
		foreach ($bannerData as $info) {
			self::formatInfo($info);
			$bannerList[] = $info;
		}

		$result = [
			'bannerList' => $bannerList,
			'bannerCount' => mShopCarouselBanner::getBannerCount($data),
		];

		return $result;
	}

	public static function admAddBanner($data, $adminUid)
	{
		$scenes = 'create';

        if($data['type'] != ShopCarouselBanner::TYPE_FLASH_MODULE && $data['type'] != ShopCarouselBanner::TYPE_PINTUAN) {
            if (!vShopBanner::validate($data, $scenes)) {
                $msg = vShopBanner::firstError();
                die($msg);
            }
        }

		$link = self::formatLink($data['link_type'], $data['link'], $data['visible_user'], 'admin');

		$bannerInfo = [
			'banner' => $data['banner'],
			'title' => $data['title'],
			'banner_desc' => $data['banner_desc'],
			'start_time' => $data['start_time'],
			'end_time' => $data['end_time'],
			'show_type' => $data['show_type'],
			'show_dest_id' => isset($data['show_dest_id']) ? $data['show_dest_id'] : 0,
			'type' => $data['type'],
			'link_dest' => $data['link'],
			'link' => $link,
			'link_type' => $data['link_type'],
			'visible_user' => $data['visible_user'],
			'visible_time' => $data['visible_time'],
            'is_grab' => isset($data['is_grab']) ? $data['is_grab'] : 0,
            'goods_id' => isset($data['goods_id']) ? implode(',', $data['goods_id']) : '',
            'commend' => $data['commend'],
            'style' => isset($data['style']) ? $data['style'] : 0,
			'sort' => $data['sort'],
			'admin_id' => $adminUid
		];
//		if ($data['type'] == ShopCarouselBanner::TYPE_SEARCH_RESULTS) {
//			$bannerInfo['banner_desc'] = $data['searchword'];
//		}
		$bannerId = mShopCarouselBanner::addBanner($bannerInfo);

		if(isset($data['is_grab'])) {
            self::admSaveBannerGrabConfig($bannerId, $data);
        }

		return $bannerId;
	}

	public static function admUpdateBannerInfoById($bannerId, $data, $adminUid)
	{
		$scenes = 'update';
		if($data['type'] != ShopCarouselBanner::TYPE_FLASH_MODULE && $data['type'] != ShopCarouselBanner::TYPE_PINTUAN) {
            if (!vShopBanner::validate($data, $scenes)) {
                $msg = vShopBanner::firstError();
                die($msg);
            }
        }


		$link = self::formatLink($data['link_type'], $data['link'], $data['visible_user'], 'admin');

		$bannerInfo = [
			'banner' => $data['banner'],
			'title' => $data['title'],
			'banner_desc' => $data['banner_desc'],
			'start_time' => $data['start_time'],
			'end_time' => $data['end_time'],
			'show_type' => $data['show_type'],
			'show_dest_id' => isset($data['show_dest_id']) ? $data['show_dest_id'] : 0,
			'type' => $data['type'],
			'link_dest' => $data['link'],
			'link' => $link,
			'link_type' => $data['link_type'],
			'visible_user' => $data['visible_user'],
			'visible_time' => $data['visible_time'],
            'is_grab' => isset($data['is_grab']) ? $data['is_grab'] : 0,
            'goods_id' => isset($data['goods_id']) ? implode(',', $data['goods_id']) : '',
            'commend' => $data['commend'],
            'style' => isset($data['style']) ? $data['style'] : 0,
			'sort' => $data['sort'],
			'admin_id' => $adminUid
		];
//		if ($data['type'] == ShopCarouselBanner::TYPE_SEARCH_RESULTS) {
//			$bannerInfo['banner_desc'] = $data['searchword'];
//		}
		$bannerId = mShopCarouselBanner::updateBannerInfoById($bannerId, $bannerInfo);

        if(isset($data['is_grab'])) {
            self::admSaveBannerGrabConfig($bannerId, $data);
        }

		return $bannerId;
	}

    private static function admSaveBannerGrabConfig($bannerId, $data)
    {
        $bannerGrabConfig = [
            'banner_id' => $bannerId,
            'grab_type' => $data['grab_type'],
            'tags' => $data['tags'],
            'edittime' => date('Y-m-d H:i:s'),
            'status' => $data['is_grab'] == ShopCarouselBanner::IS_GRAB ? mShopBannerGrabConfig::STATUS_NORMAL : mShopCarouselBanner::STATUS_DELETE
        ];

        $configInfo = mShopBannerGrabConfig::getInfo(['banner_id' => $bannerId, 'status' => mShopBannerGrabConfig::STATUS_NORMAL]);
        if($configInfo) {
            $result = mShopBannerGrabConfig::updateByBannerId($bannerId, $bannerGrabConfig);
        } else {
            $result = mShopBannerGrabConfig::add($bannerGrabConfig);
        }
        return $result;
    }

	public static function admDelBannerById($bannerId)
	{
		return mShopCarouselBanner::delBannerById($bannerId);
	}

	public static function admGetBannerPage($bannerId, $where)
	{
		$result = mShopCarouselBanner::getBannerPage($where);
		$bannerKey = array_search($bannerId, $result);
		$bannerKey++;
		return $bannerKey;
	}

	public static function getCarouselBanner($time, $count)
	{
		return mShopCarouselBanner::getCarouselBannerList($time, $count);
	}

	/*
	 * 获取开始时间和结束时间之间相差的时间
	 * **/
	public static function getCalculationDiff($data)
	{
		foreach ($data as $key => $value) {

			$data[$key]['time_sum'] = self::getTimeDiff(strtotime($value['start_time']), strtotime($value['end_time']));
		}

		return $data;
	}

	public static function admGetBannerPosList($params = [])
	{
	    $where = [];
		if(isset($params['start_time']) && $params['start_time']) {
		    $where['start_time[<=]'] = $params['start_time'];
        }

		if(isset($params['end_time']) && $params['end_time']) {
		    $where['end_time[>=]'] = $params['end_time'];
        }

		if((isset($params['start_time']) && !$params['start_time']) && (isset($params['end_time']) && !$params['end_time'])) {
            $time = date('Y-m-d H:i:s');
            $where = [
                'start_time[<=]' => $time,
                'end_time[>=]' => $time
            ];
        }

		if($where) {
		    $where = array_filter(array_merge($where, ['status' => mShopCarouselBannerPos::STATUS_NORMAL]));
        }

		$bannerPosList = mShopCarouselBannerPos::getCarouselBannerPosList();
		$bannerData = mShopCarouselBanner::select('*', $where);
		$bannerList = [];
		foreach ($bannerData as $info) {
			self::formatInfo($info);
			$bannerList[] = $info;
		}

		foreach ($bannerPosList as $key => $value) {
			foreach ($bannerList as $val) {
				if ($value['id'] == $val['show_type']) {
					$bannerPosList[$key]['son'][] = $val['banner'];
				}
			}
		}

		return $bannerPosList;
	}

	public static function admAddBannerPos($data, $uid)
	{
		$data['admin_id'] = $uid;
		$data['addtime'] = date('Y-m-d H:i:s');
		$data['edittime'] = date('Y-m-d H:i:s');
		return mShopCarouselBannerPos::addBannerPos($data);
	}

	public static function admUpdateBannerPos($id, $data, $uid)
	{
		$data['admin_id'] = $uid;
		$data['edittime'] = date('Y-m-d H:i:s');
		return mShopCarouselBannerPos::updateBannerPos($id, $data);
	}

	public static function admDelBannerPos($id, $uid)
	{
		return mShopCarouselBannerPos::delBannerPos($id, $uid);
	}

	public static function getBannerPosInfoById($id)
	{
		return mShopCarouselBannerPos::get('*', ['id' => $id]);
	}

	/*
	 * 计算开始时间和结束时间之间相差的时间
	 * **/
	private static function getTimeDiff($startTime, $endTime)
	{
		if ($startTime > $endTime) {

            $startTime = $endTime;
            $endTime = $startTime;
		}

		if (time() < $startTime) {

			return $timeSum = 0;
		}

		$timeDiff = $endTime - $startTime;
		$days = intval($timeDiff / 86400);
		$remain = $timeDiff % 86400;
		$hours = intval($remain / 3600);
		$remain = $remain % 3600;
		$min = intval($remain / 60);
		$secs = $remain % 60;
		$timeSum = '';
		if ($days != 0) {
			$timeSum .= $days . '天';
		}
		if ($hours != 0) {
			$timeSum .= $hours . '小时';
		}
		if ($min != 0 && $hours == 0 && $days == 0) {
			$timeSum .= $min . '分';
		}
		if ($secs != 0 && $hours == 0 && $min == 0) {
			$timeSum .= $secs . '秒';
		}

		return $timeSum;
	}

	public static function formatInfo(&$info)
	{
		foreach ($info as $key => $value) {
			switch ($key) {
				case 'banner' :
					$info['banner'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['banner'], ImgUrl::IMAGE_SIZE_OP_ORI);
					break;
			}
		}
	}

	public static function formatLink($id, $param, $visibleUser = mShopCarouselBanner::STATUS_VISIBLE, $mode = 'app')
	{
		$isBase64 = false;
		$isLogin = false;
		$link = tLink::getLinkById($id);
		if ($link['link_param'] == 'urlb' && $mode != 'admin') $isBase64 = true;
//        if($visibleUser != mShopCarouselBanner::STATUS_VISIBLE) $isLogin = true;
		return tLink::format($id, $param, $isBase64, $isLogin);
	}

	public static function getSecondCateBanner($cateIds, $time)
	{
		$secClassifyBanner = mShopCarouselBanner::getMultiSecondClassifyBannerInfos($cateIds, $time);
		foreach ($secClassifyBanner as $k => $v) {
			self::formatInfo($secClassifyBanner[$k]);
			$secClassifyBanner[$k]['link'] = self::formatLink($secClassifyBanner[$k]['link_type'], $secClassifyBanner[$k]['link_dest']);
		}

		return $secClassifyBanner;
	}

	public static function checkCateId($secondCateId, $startTime, $endTime)
	{
		if (!$startTime || !$endTime) {
			throw new \Exception('时间段不能为空');
		}
		$classifyName = ShopCategoryClassify::get('classify_name', [
			'id' => $secondCateId,
			'status' => ShopCategoryClassify::STATUS_NORMAL
		]);
		if (!$classifyName) {
			throw new \Exception('二级类目不存在 , 请检查');
		}
		$is_exist = mShopCarouselBanner::get('*', [
			'OR' => [
				'AND #1' => [
					'start_time[<]' => $startTime,
					'end_time[>]' => $startTime,
				],
				'AND #2' => [
					'start_time[<]' => $endTime,
					'end_time[>]' => $endTime,
				],
				'AND #3' => [
					'start_time[>]' => $startTime,
					'end_time[<]' => $endTime,
				],
			],
			'show_dest_id' => $secondCateId,
			'status' => mShopCarouselBanner::STATUS_NORMAL
		]) ? true : false;
		if ($is_exist) throw new \Exception('该类目在此时间段内下已存在banner');
		return $classifyName;
	}

	public static function fetchBanner($bannerType)
	{
		$carouselBanner = mShopCarouselBanner::getBannerByType($bannerType);
		$result = [];
		foreach ($carouselBanner as $info) {
			if (!isset($result[$info['type']])) {
				self::formatInfo($info);
				$info['link'] = self::formatLink($info['link_type'], $info['link_dest']);
				$info['statType'] = $info['type'] . '-' . $info['show_type'];
				$result[$info['type']] = [
					'id' => $info['id'],
					'banner' => $info['banner'],
					'link' => $info['link'],
					'type' => $info['type'],
					'title' => $info['title'],
					'statType' => $info['statType'],
                    'statSign' => self::formatStatSign($info)
				];
			}
		}
		return !empty($result) ? $result : null;
	}

    private static function getCarouseBannerExpire($currentExpire, $info)
    {
        if ($info['end_time'] != "0000-00-00 00:00:00" && strtotime($info['end_time']) < time() + $currentExpire) {
            return strtotime($info['end_time']) - time();
        }
        return $currentExpire;
    }
}